//
//  XDOrganizationController.m
//  XDEducation
//
//  Created by apple on 2017/4/25.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "XDOrganizationController.h"
#import "XDOrganizationCell.h"
#import "XDOrganizationHeaderView.h"
#import "XDOrganizationModel.h"
#import "XDMyOrgnizationController.h"
#import "XDExpericeModel.h"

//typedef enum : NSUInteger {
//    VCTypeOrganization,     //机构
//    VCTypeExperice,         //体验馆
//} VCType;

@interface XDOrganizationController ()<UIPickerViewDelegate,UIPickerViewDataSource>


/** 判断类型 0表示辅导机构 1表示体验馆 */
@property(nonatomic,assign) VCType vcType;

/** tableview HeaderView */
@property(nonatomic,strong) XDOrganizationHeaderView *tableHeaderView;

/** tableView 数据源 */
@property(nonatomic,strong) NSMutableArray *dataModelArr;

/** pickerView 的背景view */
@property(nonatomic,strong) UIView *pickerBgView;
@property(nonatomic,strong) UIPickerView *pickerView;


/** 所有省份 */
@property(nonatomic,strong) NSMutableArray *allProvinceArr;
/** 所有城市 */
@property(nonatomic,strong) NSMutableArray *allCityArr;
/** 所有区域 */
@property(nonatomic,strong) NSMutableArray *allAreaArr;


/** 省份 */
@property(nonatomic,strong) NSMutableArray *provinceArr;
/** 城市 */
@property(nonatomic,strong) NSMutableArray *cityArr;
/** 区域 */
@property(nonatomic,strong) NSMutableArray *areaArr;




@end

#define pickerViewHeight 250 * ScaleHeight

static NSString *cellId = @"OrganizationCell";

@implementation XDOrganizationController
{
    NSString *_selectedProvince;    //选择的省份
    NSString *_selectedCity;   //选择的城市
    NSString *_selectedArea;   //选择的区域
    
    NSString *_selectedProvinceid;    //选择的省份
    NSString *_selectedCityid;   //选择的城市
    NSString *_selectedAreaid;   //选择的区域
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //根据title 判断控制器类型
    if([self.title isEqualToString:@"辅导机构"]){
        self.vcType = VCTypeOrganization;    //辅导机构
    }else{
        self.vcType = VCTypeExperice;    //体验馆
    }
    [self initTableView];
    
    [self initNavigation];
}

-(void)initNavigation{
    
    UIButton *rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 45, 20)];
    [rightBtn setTitle:@"已加入" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [rightBtn addTarget:self action:@selector(rightBarButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
}


/** 初始化pickerView */
-(void)initPickerView{
    
    _pickerBgView = [[UIView alloc]init];
    _pickerBgView.frame = CGRectMake(0, ScreenH, ScreenW, pickerViewHeight + 40);
    _pickerBgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_pickerBgView];
    
    //添加 确定\取消 按钮
    UIButton *cancelBtn = [[UIButton alloc]initWithFrame:CGRectMake(15, 5, 60, 30)];
    [cancelBtn setTitleColor:ThemeColor forState:UIControlStateNormal];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [_pickerBgView addSubview:cancelBtn];
    [cancelBtn addTarget:self action:@selector(cancelPickerViewBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIButton *sureBtn = [[UIButton alloc]initWithFrame:CGRectMake(ScreenW - 15 - 60, 5, 60, 30)];
    [sureBtn setTitleColor:ThemeColor forState:UIControlStateNormal];
    [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    sureBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [_pickerBgView addSubview:sureBtn];
    [sureBtn addTarget:self action:@selector(selectPickerViewBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    
    //添加pickerView
    _pickerView = [[UIPickerView alloc]init];
    _pickerView.frame = CGRectMake(0, cancelBtn.bottom + 5, ScreenW, pickerViewHeight);
    _pickerView.backgroundColor = [UIColor whiteColor];
    _pickerView.delegate = self;
    _pickerView.dataSource = self;
    [_pickerBgView addSubview:_pickerView];
}


-(void)initTableView{
    
    [self.tableView registerNib:[UINib nibWithNibName:@"XDOrganizationCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:cellId];
    self.tableView.estimatedRowHeight = 200;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}


/**
 获取省份城市地域信息
 */
-(void)getAreaData{
    
    //获取所有数据
    NSString* filePath1 =[[NSBundle mainBundle] pathForResource:@"province" ofType:@"json"];
    NSData *provinceData = [NSData dataWithContentsOfFile:filePath1 options:NSDataReadingMappedIfSafe error:nil];
    NSMutableArray *province = [NSJSONSerialization JSONObjectWithData:provinceData options:NSJSONReadingMutableContainers error:nil];
    _allProvinceArr = province;
    
    NSString* filePath2 =[[NSBundle mainBundle] pathForResource:@"city" ofType:@"json"];
    NSData *cityData = [NSData dataWithContentsOfFile:filePath2 options:NSDataReadingMappedIfSafe error:nil];
    NSMutableArray *city = [NSJSONSerialization JSONObjectWithData:cityData options:NSJSONReadingMutableContainers error:nil];
    _allCityArr = city;
    
    NSString* filePath3 = [[NSBundle mainBundle] pathForResource:@"area" ofType:@"json"];
    NSData *areaData = [NSData dataWithContentsOfFile:filePath3 options:NSDataReadingMappedIfSafe error:nil];
    NSMutableArray *area = [NSJSONSerialization JSONObjectWithData:areaData options:NSJSONReadingMutableContainers error:nil];
    _allAreaArr = area;
    
    //获取第一条数据
    _provinceArr = [NSMutableArray array];
    _cityArr = [NSMutableArray array];
    _areaArr = [NSMutableArray array];
    
    [_provinceArr addObject:_allProvinceArr[0]];
    //初始值
    _selectedProvince = [_allProvinceArr[0] objectForKey:@"provincename"];
    _selectedProvinceid = [_allProvinceArr[0] objectForKey:@"provinceid"];
    
    if (_provinceArr.count > 0) {
        for (NSDictionary *dict in _allCityArr) {
            NSDictionary *provinceDict = [_provinceArr firstObject];
             NSNumber * provinceid = [provinceDict objectForKey:@"provinceid"];
            
            if ([[dict objectForKey:@"provinceid"] isEqualToNumber:provinceid]) {
                [_cityArr addObject:dict];
            }
        }
        _selectedCity = [[_cityArr firstObject] objectForKey:@"cityname"];
        _selectedCityid = [[_cityArr firstObject] objectForKey:@"cityid"];
    }
    
    if (_cityArr.count > 0) {
        for (NSDictionary *dict in _allAreaArr) {
            NSDictionary *cityDict = [_cityArr firstObject];
            NSNumber * cityid = [cityDict objectForKey:@"cityid"];
            
            if ([[dict objectForKey:@"cityid"] isEqualToNumber:cityid]) {
                [_areaArr addObject:dict];
            }
        }
        _selectedArea = [[_areaArr firstObject] objectForKey:@"areaname"];
        _selectedArea = [[_areaArr firstObject] objectForKey:@"areaid"];
    }
    
}

#pragma mark - 懒加载

-(NSMutableArray *)provinceArr{
    if (!_provinceArr) {
        _provinceArr = [NSMutableArray array];
    }
    return _provinceArr;
}

-(NSMutableArray *)cityArr{
    if (!_cityArr) {
        _cityArr = [NSMutableArray array];
    }
    return _cityArr;
}

-(NSMutableArray *)areaArr{
    if (!_areaArr) {
        _areaArr = [NSMutableArray array];
    }
    return _areaArr;
}

-(NSMutableArray *)dataModelArr{
    if (!_dataModelArr) {
        _dataModelArr = [NSMutableArray array];
    }
    return _dataModelArr;
}
#pragma mark - UIPickerView delegate
//3列数据
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{

    return 3;
}

//每一行多少个数据
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    switch (component) {
        case 0:{
            return _allProvinceArr.count;
        }
            break;
        case 1:{
            return _cityArr.count;
        }
            break;
        case 2:{
            return _areaArr.count;
        }
            break;
        default:
            return 0;
            break;
    }

}


//每一组的宽度
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{
    
    switch (component) {
        case 0:
            return ScreenW/3;
            break;
        case 1:
            return ScreenW/3;
            break;
        case 2:
            return ScreenW/3;
            break;
        default:
            return 0;
            break;
    }
}


//每组显示
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{

    switch (component) {
        case 0:
            return [_allProvinceArr[row] objectForKey:@"provincename"];
            break;
        case 1:
            return [_cityArr[row] objectForKey:@"cityname"];
            break;
        case 2:
            return [_areaArr[row] objectForKey:@"areaname"];
            break;
        default:
            return @"";
            break;
    }
}

//选中事件
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component

{
    
    if (component == 0) {
        
        //1.取省份数据
        NSDictionary *selectedProvinceDict = _allProvinceArr[row];
        
        _selectedProvince = [selectedProvinceDict objectForKey:@"provincename"];
        _selectedProvinceid = [selectedProvinceDict objectForKey:@"provinceid"];
        [_cityArr removeAllObjects];
        //2.取city数据
        if (selectedProvinceDict != nil) {
            
            
            for (NSDictionary *dict in _allCityArr) {
                
                NSNumber * provinceid = [selectedProvinceDict objectForKey:@"provinceid"];

                if ([[dict objectForKey:@"provinceid"] isEqualToNumber:provinceid]) {
                    
                    [_cityArr addObject:dict];
                }
                
            }
            _selectedCity = [[_cityArr firstObject] objectForKey:@"cityname"];
            _selectedCityid = [[_cityArr firstObject] objectForKey:@"cityid"];
        }else{
            
            _cityArr = nil;
        }
        //3.取区域数据
        [_areaArr removeAllObjects];
        
        if (_cityArr.count > 0) {
            
            for (NSDictionary *dict in _allAreaArr) {
                
                NSDictionary *cityDict = _cityArr[0];
                
                NSNumber * cityid = [cityDict objectForKey:@"cityid"];
    
                if ([[dict objectForKey:@"cityid"] isEqualToNumber:cityid]) {
                    [_areaArr addObject:dict];
                }
            }
            _selectedArea = [[_areaArr firstObject] objectForKey:@"areaname"];
            _selectedAreaid = [[_areaArr firstObject] objectForKey:@"areaid"];
        }else{
            
            _areaArr = nil;
        }
        
        //二三列选中第一个
        [pickerView selectRow:0 inComponent:1 animated:YES];
        [pickerView selectRow:0 inComponent:2 animated:YES];
        
        [pickerView selectedRowInComponent:1];
        
        [pickerView reloadComponent:1];
        
        [pickerView selectedRowInComponent:2];
        
        [pickerView reloadComponent:2];
        
    }
    
    if (component==1) {
        
        //1.取城市数据
        NSDictionary *selectedProvinceDict = _allProvinceArr[row];
        [_areaArr removeAllObjects];
        if (selectedProvinceDict != nil && _cityArr.count > 0) {
            
            NSDictionary *cityDict = _cityArr[row];
            
            _selectedCity = [cityDict objectForKey:@"cityname"];
            _selectedCityid = [cityDict objectForKey:@"cityid"];
            
            NSNumber * cityid = [cityDict objectForKey:@"cityid"];
            
            for (NSDictionary *dict in _allAreaArr) {
            
                if ([[dict objectForKey:@"cityid"] isEqualToNumber:cityid]) {
                    [_areaArr addObject:dict];
                }
            }
            _selectedArea = [[_areaArr firstObject] objectForKey:@"areaname"];
            _selectedAreaid = [[_areaArr firstObject] objectForKey:@"areaid"];
        }else{
            
        }
        
        [pickerView selectRow:0 inComponent:2 animated:YES];
    }

    if (component == 2) {
        
        if (_areaArr.count == 0) {
            return;
        }
        _selectedArea = [_areaArr[row] objectForKey:@"areaname"];
        _selectedAreaid = [_areaArr[row] objectForKey:@"areaid"];
    }
    
    [pickerView reloadComponent:2];
    
    NSLog(@"%@-%@-%@",_selectedProvince,_selectedCity,_selectedArea);
    
    
    //在这设置tableview headerView的值
    _tableHeaderView.provinceLabel.text = _selectedProvince;
    _tableHeaderView.cityLabel.text = _selectedCity;
    _tableHeaderView.areaLabel.text = _selectedArea;
    
}


//修改pickView 字体样式
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    
    UILabel* pickerLabel = (UILabel*)view;
    
    if (!pickerLabel){
        
        pickerLabel = [[UILabel alloc] init];
        
        // Setup label properties - frame, font, colors etc
        //adjustsFontSizeToFitWidth property to YES
        
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        
        [pickerLabel setFont:[UIFont boldSystemFontOfSize:16]];
        
    }
    // Fill the label text here
    pickerLabel.text = [self pickerView:pickerView titleForRow:row forComponent:component];
    
    return pickerLabel;
    
}


#pragma mark - tableview delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return 70;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    _tableHeaderView = [[XDOrganizationHeaderView alloc]init];
    WeakSelf(weakself)
    //选取城市
    _tableHeaderView.headerViewBlock = ^(){
        
        if (weakself.pickerBgView != nil) {
            return ;
        }
        [weakself getAreaData];
    
        [weakself initPickerView];
        
        [UIView animateWithDuration:0.5 animations:^{
            weakself.pickerBgView.frame = CGRectMake(0, ScreenH - pickerViewHeight - 50  - 40, ScreenW, pickerViewHeight + 40);
        }];
        
    };
    
    //查找block
    _tableHeaderView.searchBlock = ^(){
        [weakself initNetworkingWithRefreshStatus:RefreshStatePullDown];
    };
    
    return _tableHeaderView;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.dataModelArr.count;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    XDOrganizationCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    
    if (self.vcType == VCTypeOrganization) {     //判断cell类型   0表示辅导机构 1表示体验馆
        
        cell.orgModel = self.dataModelArr[indexPath.row];
        cell.cellType = CellTypeOrg;
    }else{
        
        cell.expericeModel = self.dataModelArr[indexPath.row];
        cell.cellType = CellTypeExperience;
    }
    
    //加入block
    WeakSelf(weakself)
    cell.joinedBlock =^(NSInteger dataId){
        
        [weakself joinOrgNetworkWithDataId:dataId andIndex:indexPath.row];
    };
    return cell;
}

#pragma mark - 点击事件处理

-(void)rightBarButtonClicked{
    XDMyOrgnizationController *vc = [[XDMyOrgnizationController alloc]init];
    vc.title = [NSString stringWithFormat:@"我的%@",self.title];
    vc.vcType = self.vcType;
    [self.navigationController pushViewController:vc animated:YES];

}

/**
 pickerView 取消按钮
 */
-(void)cancelPickerViewBtnClicked{

    [self clearData];
    
    [self removePickerView];
}

//清除数据
-(void)clearData{
    
    _selectedProvince = nil;
    _selectedCity = nil;
    _selectedArea = nil;
    
    _selectedProvinceid = nil;
    _selectedAreaid = nil;
    _selectedCityid = nil;
    
    _tableHeaderView.provinceLabel.text = @"省份";
    _tableHeaderView.cityLabel.text = @"市";
    _tableHeaderView.areaLabel.text = @"县";
}

/**
 pickerView 确定按钮
 */
-(void)selectPickerViewBtnClicked{
    
    [self removePickerView];
}


-(void)removePickerView{
    
    [UIView animateWithDuration:0.5 animations:^{
        
        _pickerBgView.frame = CGRectMake(0, ScreenH, ScreenW, pickerViewHeight + 40);
        
    } completion:^(BOOL finished) {
        _pickerBgView = nil;
        [_pickerBgView removeFromSuperview];
    }];

}


#pragma mark - 网络请求
-(void)initNetworkingWithRefreshStatus:(RefreshState)status{

    NSLog(@"%@-%@-%@",_selectedProvince,_selectedCity,_selectedArea);
    NSLog(@"%@-%@-%@",_selectedProvinceid,_selectedCityid,_selectedAreaid);
    
    if(_selectedProvinceid == nil){
        [MBProgressHUD showError:@"请选择城市"];
        return;
    }
    
    NSDictionary *dict;
    
    if(_selectedAreaid == nil){
        
        dict = @{@"provinceid":_selectedProvinceid,
                 @"cityid":_selectedCityid};
    }else{
    
        dict = @{@"provinceid":_selectedProvinceid,
                 @"cityid":_selectedCityid,
                 @"areaid":_selectedAreaid};
    }
    
    NSString *url;
    
    if (self.vcType == VCTypeExperice) { //体验馆url
        url = BaseURL(@"aflatunMember.do?action=aflatunInfoList");
    }else{  //辅导机构url
        url = BaseURL(@"organizationMember.do?action=organizationInfoList");
    }
    
    [MBProgressHUD showHUD];
    [XDHttpTool get:url authCode:[AccountTool shareAccountTool].currentAccount.authCode params:dict success:^(id responseObj) {
        
        [MBProgressHUD hideHUD];
        NSLog(@"%@",responseObj);
        NSArray *dictArr = [responseObj objectForKey:@"t"];
        
        if ([dictArr isKindOfClass:[NSNull class]]) {
            [MBProgressHUD showError:@"没有相关数据"];
            self.dataModelArr = nil;
        }else{
            
            NSMutableArray *tempArr = [NSMutableArray array];
            for (NSDictionary *dict in dictArr) {
                //判断数据源  是体验馆还是辅导机构
                if(_vcType == VCTypeOrganization){  //机构
                    XDOrganizationModel *model = [XDOrganizationModel modelWithDict:dict];
                    [tempArr addObject:model];
                }else{  //体验馆
                    XDExpericeModel *model = [XDExpericeModel modelWithDict:dict];
                    [tempArr addObject:model];
                }
                
            }
            self.dataModelArr = tempArr;
        
        }
        [self.tableView reloadData];
        
        [self clearData];
        
    } failure:^(NSError *error) {
        
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:XDNetWorkError];
        NSLog(@"%@",error);
        
    }];
}

//加入辅助机构\体验馆
-(void)joinOrgNetworkWithDataId:(NSInteger)dataId andIndex:(NSInteger)index{
    
    NSString *url = BaseURL(@"organizationMember.do?action=joinOrganization");
    
    NSDictionary *dict = @{@"organizationId":@(dataId)};
    [MBProgressHUD showHUD];
    [XDHttpTool get:url authCode:[AccountTool shareAccountTool].currentAccount.authCode params:dict success:^(id responseObj) {
//        NSLog(@"%@",responseObj);
        [MBProgressHUD hideHUD];
        if ([[[responseObj objectForKey:@"code"] stringValue] isEqualToString:@"1000"]) {
            
            [MBProgressHUD showSuccess:[responseObj objectForKey:@"msg"]];
            

            //移除加入成功的机构 刷新tablevie
             //[self initNetworkingWithRefreshStatus:RefreshStatePullDown];
//            [self.orgModelArr removeObjectAtIndex:index];
//            [self.tableView reloadData];
        }else{
            [MBProgressHUD showError:@"加入失败"];
        }
        
        
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:XDNetWorkError];
        NSLog(@"%@",error);
    }];
}

@end
